<?php
declare (strict_types=1);

namespace app\controller;

use app\model\Task as TaskModel;
use think\facade\Request;
use think\facade\Validate;

class Task
{
    // 更新任务
    public function update()
    {
        $data = Request::post();

        $validate = Validate::rule([
            'task_id' => 'require|integer',
            'due_date' => 'date',
            'description' => 'max:500',
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $task = TaskModel::find($data['task_id']);
        if (!$task) {
            return json(['status' => 'error', 'message' => 'Task not found']);
        }

        $task->due_date = $data['due_date'] ?? $task->due_date;
        $task->description = $data['description'] ?? $task->description;
        $task->save();

        return json(['status' => 'success', 'message' => 'Task updated successfully']);
    }

    // 删除任务
    public function delete()
    {
        $data = Request::post();

        $validate = Validate::rule([
            'task_id' => 'require|integer',
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $task = TaskModel::find($data['task_id']);
        if (!$task) {
            return json(['status' => 'error', 'message' => 'Task not found']);
        }

        $task->delete();

        return json(['status' => 'success', 'message' => 'Task deleted successfully']);
    }
}
